<template>
  <view class="payment-container">
    <!-- 导航栏 -->
    <view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="back-button" @tap="goBack">
        <text class="iconfont icon-back">〈</text>
      </view>
      <view class="title">会员订阅</view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else class="content-container">
      <!-- 订单卡片 -->
      <view class="order-card">
        <view class="order-header">
          <text class="order-title">订单信息</text>
          <view class="order-status" :class="getStatusClass(orderInfo.status)">
            {{ getOrderStatusText(orderInfo.status) }}
          </view>
        </view>
        
        <view class="divider"></view>
        
        <view class="order-item">
          <text class="item-label">会员套餐</text>
          <text class="item-value">{{ orderInfo.levelName || '未获取' }}</text>
        </view>
        
        <view class="order-item">
          <text class="item-label">订阅类型</text>
          <text class="item-value">{{ getSubscriptionTypeText(orderInfo.subscriptionType) }}</text>
        </view>
        
        <view class="order-item highlight">
          <text class="item-label">支付金额</text>
          <text class="item-value price">¥{{ orderInfo.price || '0.00' }}</text>
        </view>
        
        <view class="order-details">
          <view class="detail-item">
            <text class="detail-label">订单号</text>
            <text class="detail-value order-no">{{ orderInfo.orderId || '未获取' }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">下单时间</text>
            <text class="detail-value">{{ formatDateTime(orderInfo.createTime) }}</text>
          </view>
          
          <view class="detail-item" v-if="orderInfo.payTime">
            <text class="detail-label">支付时间</text>
            <text class="detail-value">{{ formatDateTime(orderInfo.payTime) }}</text>
          </view>
        </view>
      </view>

      <!-- 微信支付 -->
      <view class="payment-options" v-if="orderInfo.status === 'WAIT_PAY'">
        <view class="pay-method">
          <image class="wechat-icon" src="/static/images/icons/wx.png" mode="aspectFit"></image>
          <view class="method-info">
            <text class="method-name">微信支付</text>
            <text class="method-desc">快捷、安全的支付方式</text>
          </view>
          <view class="method-select">
            <text class="method-selected">✓</text>
          </view>
        </view>
        
        <view class="payment-buttons">
          <button class="pay-button" @click="handlePay" :loading="isPayLoading" :disabled="isPayLoading">
            <text class="btn-text">立即支付</text>
            <text class="btn-price">¥{{ orderInfo.price || '0.00' }}</text>
          </button>
          <button class="cancel-payment-button" @click="handleCancelPayment" :disabled="isPayLoading">取消支付</button>
        </view>
      </view>
      
      <!-- 支付结果 -->
      <view class="payment-result" v-else>
        <view class="result-icon" :class="orderInfo.status === 'SUCCESS' ? 'success' : 'failed'">
          <text class="icon">{{ orderInfo.status === 'SUCCESS' ? '✓' : '!' }}</text>
        </view>
        
        <text class="result-title">{{ orderInfo.status === 'SUCCESS' ? '支付成功' : '支付失败' }}</text>
        <text class="result-desc">{{ orderInfo.status === 'SUCCESS' ? '您的会员已开通' : '请重新尝试支付' }}</text>
        
        <view class="result-btns">
          <button v-if="orderInfo.status === 'SUCCESS'" class="success-btn" @tap="navigateToMemberCenter">
            前往会员中心
          </button>
          <button v-else class="retry-btn" @tap="retryPay">
            重新支付
          </button>
          <button class="cancel-btn" @tap="goToHome">
            返回首页
          </button>
        </view>
      </view>
      
      <!-- 支付说明 -->
      <view class="payment-notice">
        <text class="notice-title">温馨提示</text>
        <view class="notice-list">
          <view class="notice-item">
            <text class="notice-dot"></text>
            <text class="notice-text">支付完成后，会员权益将立即生效</text>
          </view>
          <view class="notice-item">
            <text class="notice-dot"></text>
            <text class="notice-text">如遇支付问题，可前往"我的-订单记录"查看</text>
          </view>
          <view class="notice-item">
            <text class="notice-dot"></text>
            <text class="notice-text">退款请联系客服，处理时间1-3个工作日</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 支付结果弹窗 -->
    <view class="result-modal" v-if="showResultModal">
      <view class="modal-content">
        <view class="modal-icon" :class="payResult ? 'success' : 'failed'">
          <text class="icon">{{ payResult ? '✓' : '!' }}</text>
        </view>
        <text class="modal-title">{{ payResult ? '支付成功' : '支付失败' }}</text>
        <text class="modal-message">{{ resultMessage }}</text>
        <view class="modal-btns">
          <button class="modal-btn" @tap="closeResultModal">知道了</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
// 脚本部分保持不变
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore, useMembershipStore } from '@/stores'
import { system } from '@/utils'
import api from '@/api/modules'
import { message } from '@/utils'

// 状态和引用
const userStore = useUserStore()
const membershipStore = useMembershipStore()
const statusBarHeight = ref(system.getDeviceInfo().statusBarHeight || 0)
const loading = ref(true)
const isPayLoading = ref(false)

// 订单信息
const orderId = ref('')
const amount = ref(0)
const orderType = ref('')
const orderInfo = ref({
  orderId: '',
  levelName: '',
  price: '0.00',
  status: 'WAIT_PAY',
  createTime: '',
  payTime: null,
  subscriptionType: ''
})

// 支付结果
const showResultModal = ref(false)
const payResult = ref(false)
const resultMessage = ref('')

// 轮询检查订单状态
let checkOrderTimer = null
const checkInterval = 3000 // 3秒检查一次
const maxCheckTimes = 20 // 最多检查20次，约60秒

// 加载数据
onLoad((options) => {
  console.log('支付页面参数:', options)
  
  if (options.orderId) {
    orderId.value = options.orderId
  }
  
  if (options.amount) {
    amount.value = parseFloat(options.amount)
  }
  
  if (options.type) {
    orderType.value = options.type
  }
  
  fetchOrderInfo()
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (checkOrderTimer) {
    clearInterval(checkOrderTimer)
    checkOrderTimer = null
  }
})

// 获取订单信息
const fetchOrderInfo = async () => {
  if (!orderId.value) {
    uni.showToast({
      title: '订单信息不完整',
      icon: 'none'
    })
    goBack()
    return
  }
  
  loading.value = true
  
  try {
    console.log('【支付页面】开始获取订单信息, orderId:', orderId.value, '订单类型:', orderType.value);
    
    let res;
    if (orderType.value === 'vip') {
      // 获取会员订阅订单
      console.log('【支付页面】正在获取会员订阅订单信息');
      res = await api.membership.getSubscriptionOrder(orderId.value)
    } else {
      // 获取普通订单
      console.log('【支付页面】正在获取普通订单信息');
      res = await api.order.getOrderDetail(orderId.value)
    }
    
    console.log('【支付页面】获取到的订单信息:', JSON.stringify(res));
    
    if (res && res.code === 200 && res.data) {
      // 调试日志：查看返回的数据结构
      console.log('【支付页面】订单数据结构:', JSON.stringify(res.data));
      
      // 处理 attach 参数解析订阅类型
      let subscriptionType = 'MONTHLY'; // 默认月卡
      if (res.data.localOrder?.attach) {
        const attachParts = res.data.localOrder.attach.split('_');
        console.log('【支付页面】订单附加数据解析:', attachParts);
        if (attachParts.length >= 3) {
          subscriptionType = attachParts[2];
          console.log('【支付页面】识别到订阅类型:', subscriptionType);
        }
      }
      
      // 处理创建时间格式化
      let formattedCreateTime = 'Unknown';
      if (res.data.localOrder?.createdAt && Array.isArray(res.data.localOrder.createdAt)) {
        // 后端返回的是数组格式的日期 [year, month, day, hour, minute, second]
        const dateArr = res.data.localOrder.createdAt;
        formattedCreateTime = `${dateArr[0]}-${String(dateArr[1]).padStart(2, '0')}-${String(dateArr[2]).padStart(2, '0')} ${String(dateArr[3]).padStart(2, '0')}:${String(dateArr[4]).padStart(2, '0')}:${String(dateArr[5]).padStart(2, '0')}`;
      } else if (res.data.createTime) {
        formattedCreateTime = res.data.createTime;
      }
      
      // 处理支付时间格式化
      let formattedPayTime = null;
      if (res.data.localOrder?.payTime && Array.isArray(res.data.localOrder.payTime)) {
        const dateArr = res.data.localOrder.payTime;
        formattedPayTime = `${dateArr[0]}-${String(dateArr[1]).padStart(2, '0')}-${String(dateArr[2]).padStart(2, '0')} ${String(dateArr[3]).padStart(2, '0')}:${String(dateArr[4]).padStart(2, '0')}:${String(dateArr[5]).padStart(2, '0')}`;
      } else if (res.data.payTime) {
        formattedPayTime = res.data.payTime;
      }
      
      // 获取套餐名称
      let levelName = res.data.localOrder?.subject || '会员套餐';
      // 根据订阅类型调整套餐名称
      if (subscriptionType === 'WEEKLY') {
        levelName = '周卡会员';
      } else if (subscriptionType === 'MONTHLY') {
        levelName = '月卡会员';
      } else if (subscriptionType === 'QUARTERLY') {
        levelName = '季卡会员';
      } else if (subscriptionType === 'YEARLY') {
        levelName = '年卡会员';
      } else if (subscriptionType === 'TEMP') {
        levelName = '临时卡';
      }
      
      // 正确映射订单数据到本地对象
      orderInfo.value = {
        orderId: res.data.localOrder?.outTradeNo || res.data.orderId || res.data.id,
        levelName: levelName,
        // ✅ 修正：统一使用金额计算，不硬编码
        price: ((res.data.localOrder?.amount || res.data.amount || amount.value) / 100).toFixed(1),
        status: res.data.status || res.data.localOrder?.status || 'WAIT_PAY',
        createTime: formattedCreateTime,
        payTime: formattedPayTime,
        subscriptionType: subscriptionType
      }
      
      // 调试信息
      console.log('【支付页面】处理后的订单信息:', JSON.stringify(orderInfo.value));
      
      // 如果订单未支付，开始轮询检查状态
      if (orderInfo.value.status === 'WAIT_PAY') {
        startCheckOrderStatus()
      }
    } else {
      uni.showToast({
        title: res?.message || '获取订单信息失败',
        icon: 'none'
      })
      console.error('【支付页面】订单信息无效:', res);
    }
  } catch (error) {
    console.error('【支付页面】获取订单信息失败:', error)
    uni.showToast({
      title: error.message || '获取订单信息失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 处理支付失败
const handlePayFail = async (err) => {
  if (checkOrderTimer) {
    clearInterval(checkOrderTimer);
    checkOrderTimer = null;
  }
  if (err.errMsg && err.errMsg.includes('cancel')) {
    await api.payment.cancelPayment(orderInfo.value.orderId);
    orderInfo.value.status = 'CLOSED';
    uni.showToast({ title: '已取消支付', icon: 'success' });
    setTimeout(() => goBack(), 1500);
  } else {
    orderInfo.value.status = 'FAILED';
    uni.showToast({ title: '支付失败，请重试', icon: 'none' });
  }
};

// 开始轮询检查订单状态
const startCheckOrderStatus = () => {
  let checkTimes = 0;
  
  // 清除可能存在的旧定时器
  if (checkOrderTimer) {
    clearInterval(checkOrderTimer);
  }
  
  // 创建新的定时器
  checkOrderTimer = setInterval(async () => {
    // 如果订单已经关闭或失败，停止轮询
    if (orderInfo.value.status === 'CLOSED' || 
        orderInfo.value.status === 'FAILED' || 
        orderInfo.value.status === 'SUCCESS') {
      clearInterval(checkOrderTimer);
      checkOrderTimer = null;
      return;
    }
    
    checkTimes++;
    
    try {
      // 检查订单状态
      let res;
      if (orderType.value === 'vip') {
        res = await api.membership.getSubscriptionOrder(orderId.value);
      } else {
        res = await api.order.getOrderDetail(orderId.value);
      }
      
      console.log('轮询检查订单状态:', res);
      
      if (res && res.code === 200 && res.data) {
        const newStatus = res.data.status || res.data.localOrder?.status || 'WAIT_PAY';
        console.log('当前订单状态:', newStatus, '原状态:', orderInfo.value.status);
        
        // 更新订单状态
        orderInfo.value.status = newStatus;
        
        // 根据状态处理
        if (newStatus === 'SUCCESS' || newStatus === 'PAID') {
          clearInterval(checkOrderTimer);
          checkOrderTimer = null;
          showPaymentResult(true, '支付成功');
          refreshUserInfo();
        } else if (newStatus === 'CLOSED' || newStatus === 'CANCELLED') {
          clearInterval(checkOrderTimer);
          checkOrderTimer = null;
          // 不显示失败提示，因为可能是用户主动取消
        } else if (newStatus === 'FAILED') {
          clearInterval(checkOrderTimer);
          checkOrderTimer = null;
          showPaymentResult(false, '支付失败，请重试');
        }
      }
    } catch (error) {
      console.error('检查订单状态失败:', error);
    }
    
    // 达到最大检查次数后停止
    if (checkTimes >= maxCheckTimes) {
      clearInterval(checkOrderTimer);
      checkOrderTimer = null;
    }
  }, checkInterval);
};

// 刷新用户信息
const refreshUserInfo = async () => {
  try {
    // 刷新用户基本信息
    await userStore.getUserInfo(true)
    
    // 如果是会员订单，重新获取会员信息
    if (orderType.value === 'vip') {
      await membershipStore.getMembershipInfo()
    }
  } catch (error) {
    console.error('刷新用户信息失败:', error)
  }
}

// 在发起支付前先确保用户已绑定微信openid
const ensureWechatBinding = async () => {
  try {
    const userId = userStore.userId;
    
    // 确保userId存在
    if (!userId) {
      uni.showToast({
        title: '用户信息获取失败，请重新登录',
        icon: 'none'
      });
      return false;
    }
    
    console.log('检查微信绑定状态, userId:', userId);
    
    // 检查用户是否已绑定微信
    const res = await api.wechat.getUserWechat(userId);
    
    // 已绑定微信，直接返回true
    if (res && res.code === 200 && res.data && res.data.miniappOpenid) {
      console.log('用户已绑定微信:', res.data.miniappOpenid);
      return true;
    }
    
    console.log('用户未绑定微信，准备授权');
    
    // 未绑定微信，需要获取授权
    return new Promise((resolve) => {
      uni.showModal({
        title: '微信支付授权',
        content: '完成支付需要获取您的微信授权',
        success: (res) => {
          if (res.confirm) {
            // 用户同意授权，获取微信code
            uni.login({
              provider: 'weixin',
              success: async (loginRes) => {
                if (loginRes.code) {
                  console.log('获取微信code成功:', loginRes.code);
                  
                  // 绑定openid到用户账号
                  const bindRes = await api.wechat.bindOpenidToUser({
                    userId: userId,
                    code: loginRes.code
                  });
                  
                  if (bindRes && bindRes.code === 200) {
                    uni.showToast({
                      title: '授权成功',
                      icon: 'success'
                    });
                    resolve(true);
                  } else {
                    console.error('绑定微信失败:', bindRes);
                    uni.showToast({
                      title: '微信授权失败: ' + (bindRes?.message || '未知错误'),
                      icon: 'none'
                    });
                    resolve(false);
                  }
                } else {
                  console.error('获取微信code失败:', loginRes);
                  uni.showToast({
                    title: '获取微信授权失败',
                    icon: 'none'
                  });
                  resolve(false);
                }
              },
              fail: (err) => {
                console.error('微信登录失败:', err);
                uni.showToast({
                  title: '微信登录失败',
                  icon: 'none'
                });
                resolve(false);
              }
            });
          } else {
            uni.showToast({
              title: '您取消了微信授权，无法完成支付',
              icon: 'none'
            });
            resolve(false);
          }
        }
      });
    });
  } catch (error) {
    console.error('检查微信绑定失败:', error);
    uni.showToast({
      title: '检查微信绑定状态失败: ' + error.message,
      icon: 'none'
    });
    return false;
  }
};

// 处理支付
const handlePay = async () => {
  if (isPayLoading.value) return;
  isPayLoading.value = true;
  
  try {
    console.log('【支付页面】开始处理支付, orderId:', orderInfo.value.orderId);
    
    if (!orderInfo.value.orderId) {
      message.error('订单ID为空，无法发起支付');
      return;
    }
    
    // 准备支付参数
    const payParams = {
      orderId: orderInfo.value.orderId,
      orderType: orderType.value,
      payMethod: 'wxpay',
      clientIp: '127.0.0.1',
      userId: userStore.userId // 确保传递用户ID
    };
    
    console.log('【支付页面】支付参数:', JSON.stringify(payParams));
    
    // 调用支付接口
    const payRes = await api.membership.createOrder(payParams);
    console.log('【支付页面】支付请求响应:', JSON.stringify(payRes));
    
    if (payRes.code !== 200 || !payRes.data) {
      console.error('【支付页面】创建支付交易失败:', payRes.message);
      message.error(payRes.message || '创建支付交易失败');
      isPayLoading.value = false;
      return;
    }
    
    // 获取支付参数
    const paymentParams = payRes.data;
    console.log('【支付页面】获取到支付参数:', JSON.stringify(paymentParams));
    
    // 服务器直接返回的是支付参数，无需再次提取payment字段
    if (!paymentParams) {
      console.error('【支付页面】支付参数为空');
      message.error('获取支付参数失败');
      isPayLoading.value = false;
      return;
    }
    
    // 调用微信支付
    console.log('【支付页面】准备调用微信支付API, 参数:', JSON.stringify(paymentParams));
    uni.requestPayment({
      ...paymentParams,
      success: (paymentRes) => {
        console.log('【支付页面】微信支付成功响应:', JSON.stringify(paymentRes));
        handlePaymentSuccess();
      },
      fail: (error) => {
        console.error('【支付页面】微信支付失败:', JSON.stringify(error));
        
        // 处理用户取消
        if (error.errMsg.includes('cancel')) {
          console.log('【支付页面】用户取消了支付');
          message.info('您已取消支付');
        } else {
          console.error('【支付页面】支付异常:', error.errMsg);
          message.error('支付失败: ' + error.errMsg);
        }
        
        // 刷新订单状态
        setTimeout(() => {
          fetchOrderInfo();
        }, 1000);
      },
      complete: () => {
        console.log('【支付页面】支付流程完成');
        isPayLoading.value = false;
      }
    });
  } catch (error) {
    console.error('【支付页面】支付失败:', error);
    uni.showToast({
      title: error.message || '支付失败，请重试',
      icon: 'none'
    });
    isPayLoading.value = false;
  }
}

// 处理支付成功
const handlePaymentSuccess = async () => {
  console.log('【支付页面】处理支付成功回调, orderId:', orderId.value);
  
  try {
    // 修改状态
    showResultModal.value = true;
    payResult.value = true;
    resultMessage.value = '支付成功，会员权益已生效';
    console.log('【支付页面】设置支付结果弹窗显示, 结果:', payResult.value);
    
    // 刷新订单信息
    console.log('【支付页面】开始刷新订单信息');
    await fetchOrderInfo();
    
    // 处理支付成功回调
    console.log('【支付页面】调用会员服务处理支付成功回调');
    const callbackRes = await membershipStore.handlePaymentSuccess(orderId.value);
    console.log('【支付页面】处理支付回调结果:', callbackRes);
    
    if (callbackRes) {
      console.log('【支付页面】回调处理成功，准备跳转');
      // 支付成功后的操作
      setTimeout(() => {
        navigateToMemberCenter();
      }, 1500);
    } else {
      console.warn('【支付页面】回调处理失败，但继续显示成功页面');
      // 即使回调处理失败，也显示支付成功（因为微信支付已经成功）
      // 可能是因为网络问题或服务器问题导致回调失败
      // 用户可以稍后刷新会员中心查看状态
    }
  } catch (error) {
    console.error('【支付页面】处理支付回调异常:', error);
    message.error('处理支付结果异常，请稍后刷新会员中心查看状态');
  }
}

// 轮询检查订单状态
const pollOrderStatus = async () => {
  console.log('【支付页面】开始轮询检查订单状态, orderId:', orderId.value);
  
  let checkCount = 0;
  const originalStatus = orderInfo.value.status;
  console.log('【支付页面】当前订单状态:', originalStatus);
  
  checkOrderTimer = setInterval(async () => {
    checkCount++;
    console.log('【支付页面】第', checkCount, '次检查订单状态');
    
    if (checkCount > maxCheckTimes) {
      console.log('【支付页面】超过最大检查次数:', maxCheckTimes, '，停止轮询');
      clearInterval(checkOrderTimer);
      checkOrderTimer = null;
      return;
    }
    
    try {
      console.log('【支付页面】查询订单:', orderId.value);
      const res = await api.membership.getSubscriptionOrder(orderId.value);
      console.log('【支付页面】轮询检查订单状态:', res);
      
      if (res.code === 200 && res.data) {
        const currentStatus = res.data.status;
        console.log('【支付页面】当前订单状态:', currentStatus, '原状态:', originalStatus);
        
        // 状态变化且变为成功
        if (currentStatus !== originalStatus && currentStatus === 'SUCCESS') {
          console.log('【支付页面】检测到订单状态变为SUCCESS');
          clearInterval(checkOrderTimer);
          checkOrderTimer = null;
          
          // 更新订单信息并处理成功回调
          fetchOrderInfo();
          handlePaymentSuccess();
        }
      }
    } catch (error) {
      console.error('【支付页面】轮询检查订单状态出错:', error);
    }
  }, checkInterval);
  
  console.log('【支付页面】设置轮询间隔:', checkInterval, 'ms');
}

// 显示支付结果
const showPaymentResult = (result, message) => {
  payResult.value = result
  resultMessage.value = message
  showResultModal.value = true
  
  // 5秒后自动关闭
  setTimeout(() => {
    closeResultModal()
  }, 5000)
}

// 关闭结果弹窗
const closeResultModal = () => {
  showResultModal.value = false
  
  // 如果支付成功，3秒后跳转到会员中心
  if (payResult.value) {
    setTimeout(() => {
      navigateToMemberCenter()
    }, 300)
  }
}

// 重试支付
const retryPay = () => {
  // 直接调用支付方法
  handlePay()
}

// 前往会员中心
const navigateToMemberCenter = () => {
  uni.navigateTo({
    url: '/pages/membership/membership'
  })
}

// 返回首页
const goToHome = () => {
  uni.switchTab({
    url: '/pages/index/index'
  }) 
}

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 'WAIT_PAY':
      return 'status-waiting'
    case 'SUCCESS':
      return 'status-success'
    case 'CLOSED':
    case 'FAILED':
      return 'status-failed'
    case 'REFUNDED':
      return 'status-refunded'
    default:
      return 'status-waiting'
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未知'
  
  try {
    // Replace hyphens with slashes for iOS compatibility
    const formattedDateTimeStr = dateTimeStr.replace(/-/g, '/');
    const date = new Date(formattedDateTimeStr);
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    const second = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`
  } catch (error) {
    console.error('日期格式化失败:', error)
    return dateTimeStr
  }
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  switch (status) {
    case 'WAIT_PAY':
      return '待支付'
    case 'SUCCESS':
      return '已支付'
    case 'CLOSED':
      return '已关闭'
    case 'FAILED':
      return '支付失败'
    case 'REFUNDED':
      return '已退款'
    default:
      return '未知状态'
  }
}

// 获取订阅类型文本
const getSubscriptionTypeText = (type) => {
  const typeMap = {
    'WEEKLY': '周卡',
    'MONTHLY': '月卡',
    'QUARTERLY': '季卡',
    'YEARLY': '年卡',
    'TEMP': '临时卡'
  }
  return typeMap[type] || type
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 处理取消支付
const handleCancelPayment = async () => {
  try {
    // 显示确认对话框
    uni.showModal({
      title: '取消支付',
      content: '确定要取消此次支付吗？',
      success: async (res) => {
        if (res.confirm) {
          uni.showLoading({ title: '取消中...' });
          
          try {
            // 调用取消支付接口
            const result = await api.payment.cancelPayment(orderId.value);
            
            if (result && result.code === 200) {
              uni.showToast({
                title: '订单已取消',
                icon: 'success'
              });
              
              // 更新订单状态
              orderInfo.value.status = 'CLOSED';
              
              // 停止轮询
              if (checkOrderTimer) {
                clearInterval(checkOrderTimer);
                checkOrderTimer = null;
              }
              
              // 2秒后返回
              setTimeout(() => {
                goBack();
              }, 2000);
            } else {
              uni.showToast({
                title: result?.message || '取消订单失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('取消支付失败:', error);
            uni.showToast({
              title: '取消支付失败: ' + error.message,
              icon: 'none'
            });
          } finally {
            uni.hideLoading();
          }
        }
      }
    });
  } catch (error) {
    console.error('取消支付异常:', error);
    uni.showToast({
      title: '操作异常: ' + error.message,
      icon: 'none'
    });
  }
};
</script>

<style lang="scss">
.payment-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  
  .nav-bar {
    height: 88rpx;
    background: #fff;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    position: relative;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .back-button {
      position: absolute;
      left: 30rpx;
      font-size: 40rpx;
      color: #333;
      z-index: 10;
    }
    
    .title {
      width: 100%;
      text-align: center;
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300rpx;
    
    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #07c160;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20rpx;
    }
    
    .loading-text {
      font-size: 28rpx;
      color: #999;
    }
    
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  }
  
  .content-container {
    padding: 30rpx;
  }
  
  .order-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
    
    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .order-title {
              font-size: 32rpx;
              font-weight: 600;
              color: #333;
            }
            
            .order-status {
              font-size: 26rpx;
              padding: 6rpx 16rpx;
              border-radius: 24rpx;
              
              &.status-waiting {
                color: #faad14;
                background: rgba(250, 173, 20, 0.1);
              }
              
              &.status-success {
                color: #07c160;
                background: rgba(7, 193, 96, 0.1);
              }
              
              &.status-failed {
                color: #ff4d4f;
                background: rgba(255, 77, 79, 0.1);
              }
              
              &.status-refunded {
                color: #722ed1;
                background: rgba(114, 46, 209, 0.1);
              }
            }
          }
          
          .divider {
            height: 1px;
            background: #f0f0f0;
            margin-bottom: 24rpx;
          }
          
          .order-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24rpx;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .item-label {
              font-size: 28rpx;
              color: #666;
            }
            
            .item-value {
              font-size: 28rpx;
              color: #333;
              font-weight: 500;
              max-width: 60%;
              text-align: right;
              
              &.price {
                font-size: 40rpx;
                color: #fa5151;
                font-weight: 600;
              }
            }
            
            &.highlight {
              margin: 36rpx 0;
              padding: 20rpx 0;
              border-top: 1px dashed #eee;
              border-bottom: 1px dashed #eee;
            }
          }
          
          .order-details {
            margin-top: 30rpx;
            padding-top: 24rpx;
            border-top: 1px solid #f5f5f5;
            
            .detail-item {
              display: flex;
              margin-bottom: 16rpx;
              
              &:last-child {
                margin-bottom: 0;
              }
              
              .detail-label {
                width: 140rpx;
                font-size: 24rpx;
                color: #999;
              }
              
              .detail-value {
                flex: 1;
                font-size: 24rpx;
                color: #666;
                word-break: break-all;
                
                &.order-no {
                  font-family: monospace;
                }
              }
            }
          }
        }
        
        .payment-options {
          background: #fff;
          border-radius: 16rpx;
          padding: 30rpx;
          margin-bottom: 30rpx;
          box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
          
          .pay-method {
            display: flex;
            align-items: center;
            padding: 24rpx;
            background: #f9f9f9;
            border-radius: 12rpx;
            margin-bottom: 36rpx;
            
            .wechat-icon {
              width: 80rpx;
              height: 80rpx;
              margin-right: 20rpx;
            }
            
            .method-info {
              flex: 1;
              
              .method-name {
                font-size: 30rpx;
                color: #333;
                font-weight: 500;
                margin-bottom: 6rpx;
              }
              
              .method-desc {
                font-size: 24rpx;
                color: #999;
              }
            }
            
            .method-select {
              padding: 0 10rpx;
              
              .method-selected {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 40rpx;
                height: 40rpx;
                background: #07c160;
                color: #fff;
                border-radius: 50%;
                font-size: 24rpx;
              }
            }
          }
          
          .payment-buttons {
            display: flex;
            flex-direction: column;
            gap: 20rpx;
            
            .pay-button {
              width: 100%;
              height: 88rpx;
              border-radius: 44rpx;
              background: #07c160;
              box-shadow: 0 8rpx 16rpx rgba(7, 193, 96, 0.2);
              display: flex;
              align-items: center;
              justify-content: center;
              padding: 0;
              position: relative;
              
              .btn-text {
                font-size: 32rpx;
                color: #fff;
                font-weight: 500;
              }
              
              .btn-price {
                position: absolute;
                right: 40rpx;
                font-size: 28rpx;
                color: rgba(255, 255, 255, 0.9);
              }
              
              &:active {
                transform: scale(0.98);
                opacity: 0.9;
              }
              
              &[disabled] {
                background: rgba(7, 193, 96, 0.6);
                opacity: 0.8;
              }
            }
            
            .cancel-payment-button {
              width: 100%;
              height: 70rpx;
              border-radius: 35rpx;
              background: #f5f5f5;
              color: #666;
              font-size: 28rpx;
              font-weight: 500;
              display: flex;
              align-items: center;
              justify-content: center;
              padding: 0;
              position: relative;
              
              &:active {
                opacity: 0.9;
              }
            }
          }
        }
        
        .payment-result {
          background: #fff;
          border-radius: 16rpx;
          padding: 50rpx 30rpx;
          margin-bottom: 30rpx;
          box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
          display: flex;
          flex-direction: column;
          align-items: center;
          
          .result-icon {
            width: 120rpx;
            height: 120rpx;
            border-radius: 60rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 30rpx;
            color: #fff;
            font-size: 60rpx;
            
            &.success {
              background: #07c160;
            }
            
            &.failed {
              background: #fa5151;
            }
          }
          
          .result-title {
            font-size: 36rpx;
            font-weight: 600;
            color: #333;
            margin-bottom: 16rpx;
          }
          
          .result-desc {
            font-size: 28rpx;
            color: #999;
            margin-bottom: 40rpx;
            text-align: center;
          }
          
          .result-btns {
            display: flex;
            justify-content: center;
            width: 100%;
            
            button {
              margin: 0 20rpx;
              height: 80rpx;
              line-height: 80rpx;
              padding: 0 40rpx;
              font-size: 28rpx;
              border-radius: 40rpx;
              
              &.success-btn {
                background: #07c160;
                color: #fff;
              }
              
              &.retry-btn {
                background: #07c160;
                color: #fff;
              }
              
              &.cancel-btn {
                background: #f5f5f5;
                color: #666;
              }
            }
          }
        }
        
        .payment-notice {
          background: #fff;
          border-radius: 16rpx;
          padding: 30rpx;
          box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
          
          .notice-title {
            font-size: 30rpx;
            font-weight: 600;
            color: #333;
            margin-bottom: 20rpx;
            display: block;
          }
          
          .notice-list {
            .notice-item {
              display: flex;
              align-items: flex-start;
              margin-bottom: 12rpx;
              
              &:last-child {
                margin-bottom: 0;
              }
              
              .notice-dot {
                width: 8rpx;
                height: 8rpx;
                border-radius: 4rpx;
                background: #07c160;
                margin-top: 14rpx;
                margin-right: 12rpx;
              }
              
              .notice-text {
                flex: 1;
                font-size: 26rpx;
                color: #666;
                line-height: 1.6;
              }
            }
          }
        }
        
        .result-modal {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.6);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 1000;
          
          .modal-content {
            width: 80%;
            background: #fff;
            border-radius: 20rpx;
            padding: 40rpx 30rpx;
            display: flex;
            flex-direction: column;
            align-items: center;
            
            .modal-icon {
              width: 120rpx;
              height: 120rpx;
              border-radius: 60rpx;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-bottom: 30rpx;
              
              &.success {
                background: #07c160;
              }
              
              &.failed {
                background: #fa5151;
              }
              
              .icon {
                font-size: 60rpx;
                color: #fff;
                font-weight: bold;
              }
            }
            
            .modal-title {
              font-size: 36rpx;
              font-weight: 600;
              color: #333;
              margin-bottom: 16rpx;
            }
            
            .modal-message {
              font-size: 28rpx;
              color: #666;
              margin-bottom: 30rpx;
              text-align: center;
            }
            
            .modal-btns {
              width: 100%;
              
              .modal-btn {
                width: 100%;
                height: 80rpx;
                line-height: 80rpx;
                background: #07c160;
                color: #fff;
                font-size: 30rpx;
                border-radius: 40rpx;
                
                &:active {
                  opacity: 0.9;
                }
              }
            }
          }
        }
}
</style>